/*
 * COPYRIGHT:   See COPYING in the top level directory
 * PROJECT:     ReactOS system libraries
 * FILE:        lib/crt/??????
 * PURPOSE:     Unknown
 * PROGRAMER:   Unknown
 * UPDATE HISTORY:
 *    25/11/05: Created
 */

#include <windows.h>
#include <stdio.h>
#include <malloc.h>
#include <io.h>
#include <fcntl.h>

FILE *_popen(const char*,const char*);
int _pclose(FILE*);
FILE *_popencmd(const char*,const char*);

FILE *_popen( const char *command, const char *mode )
{
  char *szCmdLine=NULL;
  char *szComSpec=NULL;
  char *s;
  FILE *pf;
  HANDLE hReadPipe, hWritePipe;
  int fd;
  BOOL result;
  STARTUPINFO StartupInfo;
  PROCESS_INFORMATION ProcessInformation;
  SECURITY_ATTRIBUTES sa = {sizeof(SECURITY_ATTRIBUTES), NULL, TRUE};

  if( command == NULL )
  {
    printf("command==null\n");
    return( NULL );
  }

  if( !CreatePipe(&hReadPipe,&hWritePipe,&sa,1024))
  {
    fprintf(stderr, "CreatePipe error\n");
    return NULL;
  }

  memset(&StartupInfo, 0, sizeof(STARTUPINFO));
  StartupInfo.cb = sizeof(STARTUPINFO);

  if (*mode == 'r' )
  {
   StartupInfo.hStdOutput = hWritePipe;
   StartupInfo.dwFlags |= STARTF_USESTDHANDLES;
  }
  else if ( *mode == 'w' )
  {
   StartupInfo.hStdInput = hReadPipe;
   StartupInfo.dwFlags |= STARTF_USESTDHANDLES;
  }

  result = CreateProcess(
    NULL,
   (char*) command,
  NULL,
  NULL,
  TRUE,
  0,
  NULL,
  NULL,
  &StartupInfo,
  &ProcessInformation);

  if (result == FALSE)
  {
    CloseHandle(hReadPipe);
    CloseHandle(hWritePipe);
    fprintf(stderr,"CreateProcess error\n");
    return NULL;
  }

  CloseHandle(ProcessInformation.hThread);
  if( *mode == 'r' )
  {
    fd = _open_osfhandle((int)hReadPipe, _O_RDONLY|_O_TEXT);
    CloseHandle(hWritePipe);
  }
  else
  {
    fd = _open_osfhandle((int)hWritePipe, _O_WRONLY|_O_TEXT);
    CloseHandle(hReadPipe);
  }

  pf = fdopen(fd,mode);
  return( pf );
}

int _pclose( FILE *pp )
{
  return fclose(pp);
}


FILE *_popencmd(const char *cmd, const char *mode)
{
  FILE *f;
  char *fullcommand, *comspec;

  comspec = getenv("ComSpec");
  if(comspec==0)
    comspec = "cmd.exe";

  fullcommand = (char*) malloc( 4 + strlen(comspec) + strlen(cmd) );
  if(fullcommand==0)
    return 0;
  sprintf(fullcommand, "%s /c %s", comspec, cmd);
  f =	_popen(fullcommand, mode);
  free(fullcommand);
  return f;
}